Repository navigation
JSpecify: support annotated type arguments from an enclosing class - #1699
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
Walkthrough
Possibly related PRs
Suggested labels: Suggested reviewers: Mergeability Score: ⚪ Minimal · up to The change is localized to qualified nested generic type handling and includes focused regression coverage; no actionable merge-blocking risk remains after normal checks and review. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…pache#836) The previously-@ignore'd test overrideAnonymousNestedClass exercises an anonymous class instantiated via a qualified new expression with two levels of generics, e.g. (this.new Wrapper<@nullable String>()).new Fn<String>() {...}, where the abstract method being overridden, Fn.apply(P p), references the OUTER class Wrapper's type variable P. Running the test (rather than assuming from the issue text) showed this was a hard, uncaught VerifyException crash, not a silently-missed diagnostic: GenericsChecks.getTreeType's NewClassTree handling only ever consulted newClassTree.getIdentifier() (Fn<String>) via PreservedAnnotationTreeVisitor, and PreservedAnnotationTreeVisitor's visitParameterizedType built the enclosing type from baseType.getEnclosingType() -- Fn's statically-declared enclosing type Wrapper<P>, with the raw type variable P, completely unconnected to the qualifier expression's actual instantiation. getTypeForSymbol's sanity-check verify() correctly caught the resulting type mismatch and threw. Adds GenericsChecks.withEnclosingTypeFromQualifier, which recovers the qualifier expression's own correctly-substituted type (recursing via the existing getTreeType, so arbitrary nesting depth is handled for free) and splices it in as the enclosing type, replacing baseType.getEnclosingType()'s incorrect result. This is separate from, and does not touch, the diamond-operator anonymous-class gap tracked in apache#1475.
d9aedea to
486a447
Compare
msridhar
left a comment
There was a problem hiding this comment.
One minor comment, otherwise LGTM!
| if (type == null) { | ||
| return null; | ||
| } |
There was a problem hiding this comment.
I don't think type can be null? Let's get rid of this check and the @Nullable parameter annotation, if I'm right
There was a problem hiding this comment.
Fixed. I should probably trust your own annotations!
Dug through this enough to find castToNonNull to confirm your comment.
There was a problem hiding this comment.
We also have a :nullaway:buildWithNullAway task that runs NullAway on itself, so those annotations are checked 🙂
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1699 +/- ##
============================================
- Coverage 87.89% 87.88% -0.01%
- Complexity 3173 3175 +2
============================================
Files 109 109
Lines 10755 10767 +12
Branches 2173 2175 +2
============================================
+ Hits 9453 9463 +10
- Misses 617 618 +1
- Partials 685 686 +1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
type is always the result of typeWithPreservedAnnotations(paramTypedTree), which is never null when called with a ParameterizedTypeTree, so the check and @nullable annotation were unreachable.
…ents Issue apache#1274 reported a missing warning when assigning a qualified inner class creation to an incompatible enclosing type. Bisecting shows the false negative was fixed by apache#1699, which corrected the enclosing type of a NewClassTree to come from the qualifier expression rather than the statically-declared enclosing type. Adds a regression test so the behavior stays fixed. Fixes apache#1274
…ents (#1703) ## Summary #1274 reports that NullAway misses a warning when a qualified inner-class creation is assigned to a variable whose *enclosing* type argument is incompatible: ```java class A<X extends @nullable Object> { class B<Y extends @nullable Object> {} } class C<X extends @nullable Object> extends A<X> { class D<Y extends @nullable Object> extends A<X>.B<Y> {} } C<@nullable String> c = new C<>(); A<String>.B<@nullable String> unused = c.new D<@nullable String>(); // should warn ``` Rather than assume the issue title described current behavior, I ran the example verbatim as a test first. On current `master` NullAway **does** report the expected error: ``` warning: [NullAway] incompatible types: Test.C<@nullable String>.D<@nullable String> cannot be converted to Test.A<String>.B<@nullable String> (Test.C<@nullable String>.D<@nullable String> is a subtype of Test.A<@nullable String>.B<@nullable String>) ``` Running the same test against `56bd5ad2` — the commit immediately preceding #1699 — it reports nothing. So this false negative was fixed as a side effect of #1699. That makes sense mechanically. Before #1699, `getTreeType` typed `c.new D<@nullable String>()` from the `D<@nullable String>` identifier alone, and `PreservedAnnotationTreeVisitor` took the enclosing type from `baseType.getEnclosingType()` — `D`'s statically-declared enclosing type `C<X>`, with `X` unsubstituted. Comparing `C<X>.D<@nullable String>` against `A<String>.B<@nullable String>` surfaces no nullability conflict, since `X` carries no annotation either way. #1699's `withEnclosingTypeFromQualifier` types the qualifier `c` instead, yielding `C<@nullable String>.D<@nullable String>`; `D`'s supertype then substitutes to `A<@nullable String>.B<@nullable String>` and the mismatch against the declared `A<String>.B<...>` becomes visible. This PR adds a regression test so the behavior stays fixed. No production code changes. ## Testing - Added `innerClassInheritingEnclosingTypeArgs` in `GenericsTests.java`, covering the reported error case plus two negative controls: a correctly-typed `@Nullable` enclosing instance, and a non-`@Nullable` one. Both must stay silent, so the test also pins down that we don't over-report here. - Negative control on the assertion itself: temporarily changed the erroring line's declared type to the correct one and confirmed the test fails with `Did not see an error on line 14 ... There were no errors`, verifying the expectation is load-bearing and not incidentally satisfied. - Confirmed the test fails (reports nothing) at `56bd5ad2` and passes on `master`. - `./gradlew :nullaway:test` — 919 tests, 0 failures. Fixes #1274 ## AI usage disclosure > I used Claude Code for this PR. It ran the issue's repro, bisected to determine the false negative had > already been fixed by my earlier PR #1699, explained the mechanism, and drafted the regression test. > I asked follow-up questions about the enclosing-type handling in `getTreeType` and > `PreservedAnnotationTreeVisitor`, and verified the test is load-bearing by mutating it locally. > I have read and understood all the changes in this PR. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Tests** * Added regression coverage for generic type arguments inherited by inner classes. * Verified compatible nullable assignments and detection of incompatible nullable-to-non-null assignments. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Summary
Un-ignores
overrideAnonymousNestedClass, which exercises an anonymous class instantiated via a qualifiednewexpression with two levels of generics:Fn.apply(P p)references the outer classWrapper's type variableP. The@Nullableannotation forPlives in the qualifier sub-expression (this.new Wrapper<@Nullable String>()), not in theFn<String>part naming the class actually being instantiated.Diagnosis
Running the ignored test (rather than assuming the issue title described the actual behavior) showed this is a hard, uncaught crash, not a silently-missed diagnostic:
GenericsChecks.getTreeType'sNewClassTreehandling only ever consultednewClassTree.getIdentifier()(Fn<String>) viaPreservedAnnotationTreeVisitor, nevernewClassTree.getEnclosingExpression()(the qualifierthis.new Wrapper<@Nullable String>()).PreservedAnnotationTreeVisitor.visitParameterizedTypebuilt the enclosing type frombaseType.getEnclosingType()—Fn's statically-declared enclosing type,Wrapper<P>, with the raw, unsubstituted type variablePstill present, completely unconnected to what the qualifier expression actually evaluates to. This is a materially different (and worse) bug than "annotations get dropped" — the enclosing type was never resolved to any real instantiation at all.getTypeForSymbol's own sanity-checkverify()correctly caught the resulting type mismatch and threw.This gap was left open deliberately by #837 ("JSpecify: initial handling of generic enclosing types for inner classes"), whose commit message states it fixed the enclosing-type case for ordinary declared types but explicitly did not yet handle
NewClassTrees.Fix
Adds
GenericsChecks.withEnclosingTypeFromQualifier, called fromgetTreeType'sNewClassTreebranch. It readsnewClassTree.getEnclosingExpression(); if present, it recursively calls the existinggetTreeTypeon that qualifier to get its own correctly-substituted, annotated type (this recursion is bounded by the qualifier-chain depth in the source, so arbitrarily deep nesting is handled for free with no new logic), then splices that in as the enclosing type viaTypeMetadataBuilder.createClassType, replacing the brokenbaseType.getEnclosingType()result. If there's no qualifying expression (the ordinary, unqualified anonymous-class case #808 already handles correctly), the type is returned unchanged.This is separate from, and does not touch, the diamond-operator anonymous-class gap tracked in #1475 (a distinct, early-bailout branch in the same method).
Fixes #836
Testing
overrideAnonymousNestedClasswith@Ignoreremoved before writing any fix, to confirm the actual failure mode (the crash above) rather than assume it from the issue text.overrideAnonymousNestedClassagain: passes, no crash, expected diagnostic reported.overrideAnonymousDeeplyNestedClass, a 3-level-deep qualified-nesting case (Wrapper.Middle.Fn), to confirm the recursive approach generalizes beyond the 2-level case in the original test.getEnclosingExpression()tonullinside the helper) and reran both tests — both failed (reproducing the original crash) without the fix, confirming they're load-bearing rather than passing vacuously. Reverted both before finalizing../gradlew :nullaway:test(full module suite): 914 tests, 0 failures, 0 errors../gradlew :nullaway:spotlessJavaCheck.AI usage disclosure
Summary by CodeRabbit
Bug Fixes
Tests